package com.cn.tous.auth.controller;


import com.alibaba.nacos.api.model.v2.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

@RestController
@RequestMapping("/user")
@RefreshScope
public class UserController {

    @Value("${auth.name}")
    private String authUser;

    @GetMapping("/info")
    public Result<String> getInfo(@AuthenticationPrincipal UserDetails userDetails){
        System.out.printf(authUser);
        return Result.success(userDetails.getUsername());
    }

    @GetMapping("/me")
    public String currentUser(Principal principal) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            Object principal1 = authentication.getPrincipal();
            if (principal instanceof UserDetails) {
                return ((UserDetails) principal).getUsername();
            } else if (principal1 instanceof String) {
                return (String) principal1; // 通常就是用户名
            }
        }
        System.out.printf(authUser);
        return "当前用户: " + principal.getName();
    }


}
